<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ page import="com.zkingsoft.constance.SystemConstance"%>
<%@ page import="com.zkingsoft.util.WebUtil"%>
<%
	String login_plat = String.valueOf(WebUtil.getSessionAttribute(SystemConstance.LOGIN_PLAT));
	String isHotelLogin = "false";
	if(SystemConstance.PLAT_HOTEL.equals(login_plat)) {
		isHotelLogin = "true";
	}
	
	String isFactoryLogin = "false";
	if(SystemConstance.PLAT_FACTORY.equals(login_plat)) {
		isFactoryLogin = "true";
	}
%>
<c:set var="path" value="${pageContext.request.contextPath }" />
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!-- 本框架基本脚本和样式 -->
<script type="text/javascript"
	src="${path }/resource/js/plugin/jquery-2.1.4.min.js"></script>
<script type="text/javascript"
	src="${path }/resource/js/systools/MBase.js"></script>
</head>
<body>
	<div class="ibox-content">
		<form class="form-horizontal" id="dataform"
			onsubmit="javascripr:return false;">
			<input type="hidden" name="tokenUrl" value="${tokenUrl}"> <input
				type="hidden" name="token" value="${token}">
			<c:if test="${obj ne null }">
				<input type="hidden" name="orderId" value="${obj.orderId }">
			</c:if>
			<div class="form-group">
				<label class="col-sm-2 control-label">酒店 </label>
				<div class="col-sm-4">
					<select class="form-control select2" dataType="*" nullmsg="酒店不能为空" 
						data-url="${path}/admin/linHotel/getAllHotels" onchange="getHotelPrice(this.value)"
						data-value="hotelId"
						data-filed="hotelName"
						data-def="${obj.hotelId}"  
						name="hotelId">
					</select>
				</div>
				<label class="col-sm-2 control-label">订单状态 </label>
				<div class="col-sm-4">
					<select class="form-control select2" name="orderState" dataType="*" nullmsg="订单状态不能为空">
						<option <c:if test="${obj.orderState eq 1}"> selected="selected"</c:if> value="1">已创建</option>
						<option <c:if test="${obj.orderState eq 2}"> selected="selected"</c:if> value="2">入库运输</option>
						<option <c:if test="${obj.orderState eq 3}"> selected="selected"</c:if> value="3">已入库</option>
						<option <c:if test="${obj.orderState eq 4}"> selected="selected"</c:if> value="4">已出库</option>
						<option <c:if test="${obj.orderState eq 5}"> selected="selected"</c:if> value="5">出库运输</option>
						<option <c:if test="${obj.orderState eq 6}"> selected="selected"</c:if> value="6">已验收</option>
					</select>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-2 control-label">总数量 <span
					class="text-danger">*</span>
				</label>
				<div class="col-sm-4">
					<input type="text" class="form-control" name="orderTotalNum"
						maxLength="9" dataType="n1-9" readonly="readonly" ignore="ignore"
						oninput="if(value.length>9)value=value.slice(0,9)"
						value="<c:out value="${obj.orderTotalNum }"></c:out>"
						nullmsg="总数量不能为空">
				</div>
				<label class="col-sm-2 control-label">总价格 <span
					class="text-danger">*</span>
				</label>
				<div class="col-sm-4">
					<input type="text" class="form-control" id="totalPrice"
						maxLength="13" dataType="/^[0-9]{1,8}(\.[0-9]{1,2})?$/" readonly="readonly" ignore="ignore"
						<%if("true".equals(isFactoryLogin) ) { %>
						value="<fmt:formatNumber type="number" value="${obj.orderTotalPrice }" pattern="0.00" maxFractionDigits="2"/>"
						<%} else { %>
						value="<fmt:formatNumber type="number" value="${obj.orderRealPrice }" pattern="0.00" maxFractionDigits="2"/>"
						<%} %>
						nullmsg="总价格不能为空">
					<input type="hidden" name="orderTotalPrice" value="${obj.orderTotalPrice }">
					<input type="hidden" name="orderRealPrice" value="${obj.orderRealPrice }">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-2 control-label">订单备注 </label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="orderRemark"
						maxLength="1000" dataType="s1-1000" ignore="ignore"
						value="<c:out value="${obj.orderRemark }"></c:out>"
						nullmsg="订单备注不能为空">
				</div>
			</div>
			<div class="form-group">
				<div id="toolbar">
					<c:if test="${obj eq null }">
					<a class="btn btn-success radius" href="javascript:;" id="addDetails"
						onclick="addLinens(this);"><i class="fa fa-plus"></i> 添加</a>
					</c:if>
				</div>
				<div class="col-sm-10" style="margin: 0 auto; float: initial;">
					<table id="mgrid">
						<thead>
							<tr>
								<c:if test="${obj eq null }">
									<th data-formatter="toDelBtn" data-align="center"
										data-field="tempId"></th>
								</c:if>
								<th data-formatter="MGrid.indexfn" data-align="center"
									data-width="30px">序号</th>
								<th data-field="typeName" data-width="30%"
									data-formatter="toSelect">布草名称</th>
								<th data-field="typeUnit" data-width="20%">单位</th>
								<th data-field="typePrice" data-width="20%" data-formatter="toPriceInput">单价（元）</th>
								<th data-field="detailsNum" data-width="20%"
									data-formatter="toInput">数量</th>
							</tr>
						</thead>
					</table>
				</div>
			</div>
			<div class="form-group ">
				<div class="col-sm-12 text-center">
					<a href="javascript:;" onclick="submit()"
						class="btn btn-success radius"><i class="fa fa-check"></i> 保存</a>&nbsp;&nbsp;&nbsp;&nbsp;
					<a class="btn btn-danger radius" href="javascript:;"
						onclick="MTools.closeForm()"><i class="fa fa-close"></i> 关闭</a>
				</div>
			</div>
		</form>
	</div>
</body>
<script type="text/javascript"
	src="${path }/resource/js/systools/MJsBase.js"></script>
<script type="text/javascript">

	function getLinTypes() {
		var opts = new Array();
		$.AjaxProxy().invoke("${path}/admin/linType/getAllTyps", function(loj) {
			for (var i = 0; i < loj.getRowCount(); i++) {
					opts.push({
						value : loj.getString(i, "typeId"),
						filed : loj.getString(i, "typeName")
					});
			}
		});
		return opts;
	}
	
	var linTypes = getLinTypes();

	function toInput(value, row, index) {
		value = value ? value : 0;
		
		<c:if test="${obj ne null }">
		return value;
		</c:if>
		<c:if test="${obj eq null }">
		
		return '<input type="number" class="form-control" oninput="if(value.length>9)value=value.slice(0,9)" dataType="n1-9" nullmsg="数量不能为空" onChange="updateNum(this.value, '
				+ index
				+ ')" value="'
				+ value
				+ '" />';
		</c:if>
	}
	
	function toPriceInput(value, row, index) {
		value = value ? value : 0;
		var isFactoryLogin = "<%=isFactoryLogin%>";
		
		<c:if test="${obj ne null}">
			if(isFactoryLogin == 'true') {
				return (row.detailsTotalPrice/row.detailsNum).toFixed(2);
			} else {
				row.realPrice = (row.detailsRealPrice/row.detailsNum).toFixed(2);
				return row.realPrice;
			}
		</c:if>
		<c:if test="${obj eq null }">
			if(isFactoryLogin == 'true') {
				return value;
			} else {
				var price = row.realPrice ? row.realPrice : '';
				return '<input type="text" class="form-control" maxLength="11" dataType="/^[0-9]{1,8}(\.[0-9]{1,2})?$/" nullmsg="单价不能为空" onChange="updatePrice(this.value, '
							+ index + ')" value="'+ price +'" />';
			}
		
		</c:if>
	}

	function toSelect(value, row, index) {
		<c:if test="${obj ne null }">
		return value;
		</c:if>
		<c:if test="${obj eq null }">
		
		var select = '<select class="form-control select2" onChange="selectTypeId(this.value, ' + index + ');" >';

		$.each(linTypes, function(i) {
			if(linTypes[i].value == row.typeId) {
				select += '<option selected="selected" value="' + linTypes[i].value + '">' + linTypes[i].filed + "</option>";
			} else {
				select += '<option value="' + linTypes[i].value + '">' + linTypes[i].filed + "</option>";
			}
		})
		select += '</select>';
		
		return select;

		</c:if>
	}

	function toDelBtn(value, row, index) {

		return '<a class="btn btn-danger radius" href="javascript:;"onclick="delLinens(\''
				+ value + '\');"><i class="fa fa-close"></i></a>';
	}
</script>
<script type="text/javascript">
	
// 	MTools.autoFullSelect();
	$('select[name="hotelId"]').load(
			$('select[name="hotelId"]').data("url"), null,
			function(response,status,xhr) {
				var _this = $('select[name="hotelId"]');
				var def = _this.data("def");
				var value =  _this.data("value");
				var field = _this.data("filed");
				
				var res = eval("("+response+")");
				
				var html = '';
				for (var i = 0; i < res.rows.length; i++) {
					if (def && ((def + "").indexOf(res.rows[i][value]) > -1)) {
						html += '<option selected="selected" value="' + res.rows[i][value] + '">' + res.rows[i][field] + "</option>";
					} else {
						html += '<option value="' + res.rows[i][value] + '">' + res.rows[i][field] + "</option>";
					}
				}
				_this.append(html);
				
				_this.trigger("change");
			}
	);
	
	$(".select2").select2();
	
	var myForm = MForm.initForm({
		invokeUrl : "${path}/admin/linOrder/addOrModify",
		afterSubmit : function() {
			parent.myGrid.serchData();
		},
	});

	var myGrid;
	var url = "";
	<c:if test="${obj ne null }">
	url = "${path}/admin/linOrderDetails/getOrderDetails?orderId=${obj.orderId }";
	
	$('select[name="hotelId"]').select2("enable", false);
	$('select[name="hotelId"]').next('span').children('span').children('span').children('span').css("background-color", "#eee");
	
	$('input[name="orderTotalNum"]').attr("readonly", "readonly");
	$('input[name="orderTotalPrice"]').attr("readonly", "readonly");
	</c:if>
	
	<c:if test="${obj eq null }">
	$('select[name="orderState"]').select2("enable", false);
	$('select[name="orderState"]').next('span').children('span').children('span').children('span').css("background-color", "#eee");
	</c:if>

	$(function() {
		myGrid = MGrid.initGrid({
			url : url,
			showColumns : false,
			showToggle : false,
			showRefresh : false,
			checkboxHeader : false,
			formatNoMatches : function() {
				return '';
			},
			toolbar : '#toolbar',
			pagination : false
		});
	});

	var typeId, typeName, typeUnit, typePrice, realPrice;
	
	function getHotelPrice(hotelId) {
		$.ajax({
			url : '${path}/admin/linType/getTypeById',
			type : 'POST',
			data : {
				id : 1,
				hotel_id : hotelId
			},
			dataType : 'json',
			async : false,
			success : function(result) {
				var linen = result.mapInfo.linen;
	
				typeId = linen.typeId;
				typeName = linen.typeName;
				typeUnit = linen.typeUnit;
				typePrice = linen.typePrice;
				realPrice = linen.realPrice;
			}
		});
		
		var gridData = $('#mgrid').bootstrapTable('getData');
// 		var typeSet = new Object();
		$.each(gridData, function(i) {
			
// 			if(typeSet.hasOwnProperty(gridData[i].typeId)) {
				
// 			} else {
				selectTypeId(gridData[i].typeId, i);
// 			}
		});
	}

	function uuid() {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for (var i = 0; i < 36; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
		s[8] = s[13] = s[18] = s[23] = "-";

		var uuid = s.join("");
		return uuid.split("-").join('');
	}

	function addLinens(_this) {

		$('#mgrid').bootstrapTable('prepend', {
			tempId : uuid(),
			typeId : typeId,
			typeName : typeName,
			typeUnit : typeUnit,
			typePrice : typePrice,
			realPrice : realPrice
		});

		$(".select2").select2();
	}

	function delLinens(tempId) {

		$('#mgrid').bootstrapTable('remove', {
			field : "tempId",
			values : [ tempId ]
		});

		$(".select2").select2();
	}

	function selectTypeId(typeId, index) {
		$.ajax({
			url : '${path}/admin/linType/getTypeById',
			type : 'POST',
			data : {
				id : typeId,
				hotel_id : $('select[name="hotelId"]').val()
			},
			dataType : 'json',
			async : false,
			success : function(result) {
				var linen = result.mapInfo.linen;
				$('#mgrid').bootstrapTable('updateRow', {
					index : index,
					row : {
						typeId : linen.typeId,
						typeName : linen.typeName,
						typeUnit : linen.typeUnit,
						typePrice : linen.typePrice,
						realPrice : linen.realPrice
					}
				});
				updateTotal();
			}
		});

		$(".select2").select2();
	}

	function updateNum(num, index) {
		$('#mgrid').bootstrapTable('updateRow', {
			index : index,
			row : {
				detailsNum : num
			}
		});
		updateTotal();
		$(".select2").select2();
	}
	
	function updatePrice(price, index) {
		$('#mgrid').bootstrapTable('updateRow', {
			index : index,
			row : {
				realPrice : price
			}
		});
		updateTotal();
		$(".select2").select2();
	}
	
	function updateTotal() {
		var gridData = $('#mgrid').bootstrapTable('getData');
		var totalNum = 0;
		var totalPrice = parseFloat("0");
		var realPrice = parseFloat("0");
		$.each(gridData, function(i) {
			var detailsNum = parseInt(gridData[i].detailsNum);
			var detailsPrice = 0.0;
			var detailsRealPrice = 0.0;
			
<%-- 			if("<%=isFactoryLogin%>" == 'true') { --%>
				detailsPrice = parseFloat(detailsNum) * parseFloat(gridData[i].typePrice);
// 			} else {
				detailsRealPrice = parseFloat(detailsNum) * parseFloat(gridData[i].realPrice);
// 			}
			console.log(detailsNum, detailsPrice, detailsRealPrice);
			
			if(!isNaN(detailsNum) && !isNaN(detailsPrice) && !isNaN(detailsRealPrice)) {
				totalNum += detailsNum;
				totalPrice += detailsPrice;
				realPrice += detailsRealPrice;
			}
		});
		if("<%=isFactoryLogin%>" == 'true') {
			$('#totalPrice').val(totalPrice.toFixed(2));
		} else {
			$('#totalPrice').val(realPrice.toFixed(2));
		}
		$('input[name="orderTotalNum"]').val(totalNum);
		$('input[name="orderTotalPrice"]').val(totalPrice.toFixed(2));
		$('input[name="orderRealPrice"]').val(realPrice.toFixed(2));
	}
	
	function submit() {
		var extendParam = new Object();
		
		var gridData = $('#mgrid').bootstrapTable('getData');
		
		var isZeroNum = false;
		console.log(gridData);
		if(gridData.length == 0) {
			layer.tips('详细数量不能为空！', '#addDetails', {tips: [2, '#c00']});
			isZeroNum = true;
		}
		
		$.each(gridData, function(i) {
			
			if(!gridData[i].hasOwnProperty("detailsNum") || gridData[i].detailsNum == null || gridData[i].detailsNum == 0) {
				layer.tips('数量不能为空！', 'th[data-field="detailsNum"]', {tips: [1, '#c00']});
				isZeroNum = true;
			}
			if("<%=isFactoryLogin%>" != 'true') {
				if(!gridData[i].hasOwnProperty("realPrice") || gridData[i].realPrice == null || gridData[i].realPrice == 0) {
					layer.tips('单价不能为空！', 'th[data-field="typePrice"]', {tips: [1, '#c00']});
					isZeroNum = true;
				}
			}
			
			console.log(gridData[i]);
			var index = 'linOrderDetails[' + i + ']'; 
			extendParam[index+'.typeId'] = gridData[i].typeId;
			extendParam[index+'.detailsNum'] = gridData[i].detailsNum;
			extendParam[index+'.typePrice'] = gridData[i].typePrice;
			extendParam[index+'.realPrice'] = gridData[i].realPrice;
			
		});
		if(!isZeroNum) {
			MForm.initForm({
				invokeUrl : "${path}/admin/linOrder/addOrModify",
				extendParam : extendParam,
				afterSubmit : function() {
					parent.myGrid.serchData();
				},
			}).submit();
		}
	}
</script>
</body>
</html>